package com.linkq.ipinyin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.linkq.ipinyin.common.utils.StringUtils;
import com.linkq.ipinyin.mapper.PayDetailsMapper;
import com.linkq.ipinyin.model.*;
import com.linkq.ipinyin.service.AppleReceiptVerifier;
import com.linkq.ipinyin.service.CustomerService;
import com.linkq.ipinyin.service.OrderService;
import com.linkq.ipinyin.utils.DateUtils;
import com.linkq.ipinyin.vo.ResultInfo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author wangpeng
 * @since 2025-06-29
 **/

@Slf4j
@RestController
@Api(value = "苹果内购", tags = {"苹果内购"})
@RequestMapping(value = "/app/applePay")
public class IapController {

    @Autowired
    private PayDetailsMapper payDetailsMapper;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private AppleReceiptVerifier receiptVerifier;

    /**
     * 接收自己APP客户端发过来的购买凭证
     *
     * @param applePayReq 苹果内购参数
     */
    @PostMapping("/setIapCertificate")
    @ResponseBody
    public ResultInfo setIapCertificate(@RequestBody ApplePayReq applePayReq) {
        int userId = customerService.getUser().getId();
        String receipt = applePayReq.getReceipt();
        String chooseEnv = applePayReq.getChooseEnv();
        String orderId = applePayReq.getOrderId();
        String productId = applePayReq.getProductId();
        log.info("IOS端发送的购买凭证。数据有 userId = {},receipt = {},chooseEnv = {}", userId, receipt, chooseEnv);
        if (StringUtils.isNotEmpty(receipt)) {
            JSONObject result = receiptVerifier.verifyReceipt(receipt);
            AppleResponse appleResponse = JSON.parseObject(result.toJSONString(), AppleResponse.class);
            if (result.getIntValue("status") == 0) {
                // 先根据originalTransactionId查询是否已存在order
                String originalTransactionId = appleResponse.getReceipt().getIn_app()[0].getOriginal_transaction_id();
                // 更新order
                Order order = orderService.selectById(orderId);
                order.setOriginalTransactionId(originalTransactionId);
                order.setStatus(2);
                order.setProductId(productId);
                order.setPayTime(new Date(Long.parseLong(appleResponse.getReceipt().getIn_app()[0].getPurchase_date_ms())));
                order.setUpdateTime(new Date());
                orderService.updateById(order);
                Customer customer = customerService.getUser();
                if (StringUtils.equals("pinyinmonthstagevip", productId)) {
                    int vipType = customer.getVipType();
                    if (vipType == 2) {
                        log.error("永久会员用户{}购买了月度会员", customer.getId());
                        return ResultInfo.error("永久会员用户购买了月度会员");
                    }
                    customer.setVipType(1);
                    customer.setExpireTime(DateUtils.dateCaculate(customer.getExpireTime() == null ? new Date() : customer.getExpireTime(), 1, Calendar.DAY_OF_MONTH));
                } else if (StringUtils.equals("allVip", productId)){
                    customer.setVipType(2);
                } else {
                    log.error("用户{}购买的商品不存在: {}", customer.getId(), productId);
                    return ResultInfo.error("用户购买的商品不存在");
                }
                customerService.updateById(customer);
                return ResultInfo.success();
            } else {
                return ResultInfo.error("支付失败");
            }
        } else {
            return ResultInfo.error("支付失败");
        }
    }

}
